<?php
declare (strict_types=1);

namespace app\course\model\coupon\admin;

use app\common\model\BaseModel;
use app\course\model\base\admin\Course;
use app\school\model\school\admin\School;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;

/**
 * 课程卡券模型
 */
class CourseCard extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'coupon';
    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';
    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'id'           => 'integer',
        'use_stime'    => 'timestamp',
        'use_etime'    => 'timestamp',
        'derive_stime' => 'timestamp',
        'derive_etime' => 'timestamp',
    ];

    /**
     * 全局查询范围
     *
     * @var [type]
     */
    protected $globalScope = ['couponType', 'mhm'];

    /**
     * 课程卡
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     *
     * @param    [type]                         $query [description]
     */
    public function scopecouponType($query)
    {
        $query->partition('p3')->where('online', request()->param('online'));
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     *
     * @param    [type]                         $coupon [description]
     */
    public static function onBeforeInsert($model)
    {
        // 卡券类型 -- 课程卡
        $model->coupon_type = 3;
        // 线上 or 线下
        $model->online = request()->param('online');
    }

    /**
     * 关联机构
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     */
    public function school(): BelongsTo
    {
        return $this->belongsTo(School::class, 'mhm_id')->bind(['school_name' => 'title']);
    }

    public function courseIdAttach(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id')->with(['coverUrl']);
    }

    /**
     * 实体卡数据
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-16
     */
    public function offline(): HasMany
    {
        return $this->hasMany(CouponOffline::class, 'coupon_id');
    }

    /**
     * 限制机构条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     *
     * @param    [type]                         $query [description]
     */
    public function scopeMhm($query)
    {
        // 如果不是平台时, 加入机构条件限制
        if (!request()->is_platform) {
            $query->where('mhm_id', request()->mhm_id);
        }
    }
}
